//
//  WFQiniuManager.m
//  imtMall
//
//  Created by lorin on 15/6/9.
//  Copyright (c) 2015年 IMT. All rights reserved.
//

#import "WFQiniuManager.h"
#import "MGConstFile.h"
#import "QNUploadManager.h"
#import "QNUploadOption.h"

#import "QN_GTM_Base64.h"
#import <CommonCrypto/CommonHMAC.h>

static NSString *ZXQiNiuScope = @"jingjibang";
static NSString *ZXQiNiuAccessKey = @"dXaB1-g-Ly6B9M5VfuG7tFXX0g1A6RO5Emxu-h-R";
static NSString *ZXQiNiuSecretKey = @"MDZDWxB6oLhrvCUTuaL9HP-PaS19jwsytJlK6UBB";

static NSString *QiNiuHost = @"https://img.jingjibang.cn";


@interface WFQiniuUploadImageOprate : NSObject

-(void)uploadQNImage:(UIImage *)image
             itemKey:(NSString *)itemKey
            groupKey:(NSString *)gorupKey
         finishBlock:(WFQiniuUploadFinshBlock)block
        percentBlock:(WFQiniuUploadPercentBlock)percentBlock;
@end

@interface WFQiniuUploadImageOprate()
@property (nonatomic,copy) WFQiniuUploadFinshBlock finishBlock;
@property (nonatomic,copy) WFQiniuUploadPercentBlock percentBlock;
@property (nonatomic,strong) NSData *uploadData;

@property (nonatomic,copy) NSString *itemKey;


@end

@implementation WFQiniuUploadImageOprate
-(void)uploadQNImage:(UIImage *)image
             itemKey:(NSString *)itemKey
            groupKey:(NSString *)gorupKey
         finishBlock:(WFQiniuUploadFinshBlock)block
        percentBlock:(WFQiniuUploadPercentBlock)percentBlock
{
    self.itemKey  = itemKey;
    self.finishBlock = block;
    self.percentBlock = percentBlock;
    self.uploadData = UIImageJPEGRepresentation(image, 0.1);
    
    
//    [WFServices.networkService.uploadService fetchUploadTokenWithUID:WF_USER_ID
//                                                            groupKey:(NSString *)gorupKey
//                                                         forFileType:self.fileType
//                                                       inUploadModle:self.uploadModel
//                                                 completion:^(AFHTTPRequestOperation *requestOpertion, WFBaseResponse *response) {
//                                                     WFFetchUploadTokenResp *resp = (WFFetchUploadTokenResp *)response;
//                                                     if (resp.resultCode == WF_REQUEST_SUCCESS) {
//                                                         NSString *token = resp.uploadToken;
//                                                         [self uploadWithToken:token];
//                                                     }
//                                                     else{
//                                                         self.finishBlock(NO,resp.errorMessage,nil);
//                                                     }
//    }
//                                                       fail:^(AFHTTPRequestOperation *requestOpertion, NSError *error) {
//                                                           self.finishBlock(NO,@"",nil);
//        
//    }];

    [self uploadWithToken:[WFQiniuManager createTokenWithScope:ZXQiNiuScope accessKey:ZXQiNiuAccessKey secretKey:ZXQiNiuSecretKey itemkey:itemKey]];
    
}

-(void)uploadWithToken:(NSString *)token
{
    QNUploadManager *uploadManage = [[QNUploadManager alloc] initWithRecorder:nil recorderKeyGenerator:nil];
    WEAK_SELF
    QNUploadOption *option = [[QNUploadOption alloc] initWithMime:nil
                                                  progressHandler:^(NSString *key, float percent) {
                                                      if (self.percentBlock) {
                                                          self.percentBlock(weakSelf.itemKey?:key,percent);
                                                      }
                                                  }
                                                           params:nil
                                                         checkCrc:NO
                                               cancellationSignal:^BOOL{
                                                   return NO;
                                               }];
    
    
    [uploadManage putData:self.uploadData
                      key:[NSString stringWithFormat:@"%@.jpg",self.itemKey]
                    token:token
                 complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                     NSLog(@"info %@ --- %@",info,resp);
//                     [self launchMailApp:[NSString stringWithFormat:@"&body=<b>%@</b> body!",info]];
                     if (self.finishBlock) {
                         if (resp) {
                             self.finishBlock(YES,weakSelf.itemKey?:key,[NSString stringWithFormat:@"%@/%@",QiNiuHost,resp[@"key"]]);
                         }
                         else{
                             
                             self.finishBlock(NO,weakSelf.itemKey?:key,nil);
                             
                         }
                     }
                 } option:option];
}
-(void)launchMailApp:(NSString *)str
{
    NSMutableString *mailUrl = [[NSMutableString alloc]init];
    //添加收件人
    NSArray *toRecipients = [NSArray arrayWithObject: @"3332634260@qq.com"];
    [mailUrl appendFormat:@"mailto:%@", [toRecipients componentsJoinedByString:@","]];
    //添加抄送
    NSArray *ccRecipients = [NSArray arrayWithObjects:@"second@example.com", @"third@example.com", nil];
    [mailUrl appendFormat:@"?cc=%@", [ccRecipients componentsJoinedByString:@","]];
    //添加密送
    NSArray *bccRecipients = [NSArray arrayWithObjects:@"fourth@example.com", nil];
    [mailUrl appendFormat:@"&bcc=%@", [bccRecipients componentsJoinedByString:@","]];
    //添加主题
    [mailUrl appendString:@"&subject=my email"];
    //添加邮件内容
    [mailUrl appendString:str];
    NSString* email = [mailUrl stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    [[UIApplication sharedApplication] openURL: [NSURL URLWithString:email]];
}
@end

@implementation WFQiniuManager
+(WFQiniuManager *)sharedManager
{
    static WFQiniuManager *_sharedManager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedManager = [WFQiniuManager new];
    });
    return _sharedManager;    
}

-(void)uploadQNImage:(UIImage *)image
             itemKey:(NSString *)itemKey
            groupKey:(NSString *)gorupKey
         finishBlock:(WFQiniuUploadFinshBlock)finishBlock
        percentBlock:(WFQiniuUploadPercentBlock)percentBlock
{
    WFQiniuUploadImageOprate *oprate = [WFQiniuUploadImageOprate new];
    [oprate uploadQNImage:image
                  itemKey:(NSString *)itemKey
                 groupKey:gorupKey
                finishBlock:finishBlock
             percentBlock:percentBlock];
}

+(NSString *)createGroupKey
{   
    return [[[NSUUID UUID] UUIDString] stringByReplacingOccurrencesOfString:@"-" withString:@""];
}
+(NSString *)createitemKey{
    return [[[NSUUID UUID] UUIDString] stringByReplacingOccurrencesOfString:@"-" withString:@""];
}


+ (NSString *)createTokenWithScope:(NSString *)scope accessKey:(NSString *)accessKey secretKey:(NSString *)secretKey itemkey:(NSString *)itemkey{
    // 1.确定上传策略
    NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] init];
    jsonDict[@"scope"] = scope;
//    jsonDict[@"saveKey"] = [NSString stringWithFormat:@".jpg"];
    [jsonDict setValue:[NSNumber numberWithLong:[[NSDate date] timeIntervalSince1970] + 24 * 3600]
forKey:@"deadline"];
    

    // 2.将上传策略序列化成为json格式:
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict
                                                       options:0
                                                         error:nil];
    
    // 3.对json序列化后的上传策略进行URL安全的Base64编码,得到如下encoded:
    NSString* encoded = [self URLSafeBase64Encode:jsonData];
    
    // 4.用SecretKey对编码后的上传策略进行HMAC-SHA1加密，并且做URL安全的Base64编码,得到如下的encoded_signed:
    NSString *encoded_signed = [self HMACSHA1:secretKey text:encoded];
    
    // 5.将 AccessKey、encode_signed 和 encoded 用 “:” 连接起来,得到如下的UploadToken:
    NSString *uploadToken=[NSString stringWithFormat:@"%@:%@:%@",accessKey,encoded_signed,encoded];
    
    return uploadToken;
}
+ (NSString *)URLSafeBase64Encode:(NSData *)text {
    
    NSString *base64 = [[NSString alloc] initWithData:[QN_GTM_Base64 encodeData:text] encoding:NSUTF8StringEncoding];
    base64 = [base64 stringByReplacingOccurrencesOfString:@"+" withString:@"-"];
    base64 = [base64 stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
    return base64;
}
+  (NSString *)HMACSHA1:(NSString *)key text:(NSString *)text {
    const char *cKey = [key cStringUsingEncoding:NSUTF8StringEncoding];
    const char *cData = [text cStringUsingEncoding:NSUTF8StringEncoding];
    char cHMAC[CC_SHA1_DIGEST_LENGTH];
    CCHmac(kCCHmacAlgSHA1, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
    NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC length:CC_SHA1_DIGEST_LENGTH];
    NSString *hash = [self URLSafeBase64Encode:HMAC];
    return hash;
}
@end

